package com.yzt.zhuju.voice;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

/**
 * 功能：音频播放的管理类
 */
public class MediaPlayerManage {

    private static MediaPlayerManage mInstance;

    private MediaPlayerManage() {
    }

    public static MediaPlayerManage getInstance() {
        if (mInstance == null) {
            mInstance = new MediaPlayerManage();
        }
        return mInstance;
    }
    public MediaPlayer startAlarm(Context context, boolean loop, String srcUrl, final VoicePlayListener voicePlayListener) {
        openSpeaker(context);
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setOnPreparedListener(mp -> {
                mediaPlayer.start();
                if (voicePlayListener != null) {
                    voicePlayListener.startPlay(mp);
                }
            });

            mediaPlayer.setOnCompletionListener(mp -> {
                mediaPlayer.release();
                if (voicePlayListener != null) {
                    voicePlayListener.completePlay(mp);
                }
            });

            mediaPlayer.setOnErrorListener((mp, what, extra) -> false);
            mediaPlayer.setDataSource(srcUrl);
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mediaPlayer;
    }

    //打开扬声器
    public void openSpeaker(Context context) {
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setMode(AudioManager.MODE_NORMAL);
            if (!audioManager.isSpeakerphoneOn()) {
                audioManager.setSpeakerphoneOn(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopAlarm(MediaPlayer mp) {
        if (mp == null) {
            return;
        }
        try {
            if (mp.isPlaying()) {
                mp.stop();
            }
            mp.release();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mp = null;
        }
    }

    public interface VoicePlayListener {

        void startPlay(MediaPlayer mp);

        void completePlay(MediaPlayer mp);
    }
}
